import {
  getTenantByUid,
  getProjectListByUserIdAndTenant,
  getPermissionByUserIdAndTenant,
} from "@/api/auth";
import { getLoginData, saveData } from "@/tools";
export default {
  //【通用级方法】添加state
  setStoreState({ commit }, data) {
    if (Object.prototype.toString.call(data) !== "[object Object]") {
      console.error(`${data} is not an Object type`);
      return;
    }
    commit("SET_STORE_STATE", data);
  },

  //清空state
  clearState({ commit }) {
    commit("SET_STORE_STATE", { operateFlag: null });
  },

  //查询租户列表信息
  queryTenantData({ dispatch, state }) {
    let { uid } = state.USER_INFO;
    return new Promise((resolve, reject) => {
      getTenantByUid({ userId: uid })
        .then((res) => {
          let { data } = res;
          let source = data?.result || [];
          saveData("TENANT_DATA", source);
          resolve(source);
        })
        .catch((error) => {
          reject(error);
        });
    });
  },

  //查询租户对应项目列表
  queryTenantProjectSourceData({ dispatch, state }) {
    let { uid } = state.USER_INFO;
    let { tenantCode } = state.ORGANIZATION;
    return new Promise((resolve, reject) => {
      getProjectListByUserIdAndTenant({ userId: uid, tenantCode })
        .then((res) => {
          let { data } = res;
          let source = data?.result || [];
          saveData("PROJECT_SOURCE", source);
          resolve(source);
        })
        .catch((error) => {
          reject(error);
        });
    });
  },

  //查询菜单相关信息
  queryPermissionData({ dispatch, state }) {
    return new Promise((resolve, reject) => {
      let { tenantCode } = state.ORGANIZATION;
      let { uid } = state.USER_INFO;
      getPermissionByUserIdAndTenant({ userId: uid, tenantCode })
        .then((res) => {
          let { data } = res;
          let source = data?.result || [];
          source.forEach((v) => {
            let { child } = v;
            v.childs = child;
          });
          //权限数据
          saveData("PERMISIONS_DATA", source);
          //配置中心
          let { childs = [] } = source.find((v) => v.menuType == 1) || {
            childs: [],
          };
          saveData("CONFIG_CENTER", childs || []);
          resolve(source);
        })
        .catch((_) => {
          console.log(_);
          reject();
        });
    });
  },
};
